<template>
    <view>
        <view class="head-content">
            <!-- #ifdef MP-WEIXIN --> 
			<top-nav :inner-title="storeInfo.shop_name" is-show-back="true" is-fixed="true" :navH="navH" :n="n" is-white="bg-white" opacity="1"></top-nav>
            <view  :style="{height: navH +'px'}"></view>
            <!-- #endif -->
			<view class="search flex">
				<view class="search-item flex">
						<image src="http://juhuijia2.birdback.org/mapi/i/run/search@3x.png"></image>
						<input value="searchData" type="text" :focus="focusSearch" placeholder="想吃什么,搜一搜～" v-model="searchData" @input="inputChange" @confirm="inputSearchChange(searchData)"></input>
						<image src="http://img1.birdback.org/a/4f/92/4f92e01ba5f5e03080c6dc54fb2277f3.png" class="empty_close" v-if=" searchData != '' " @click="emptyInput()" ></image>
				</view>
                <view class="search_text" @click="inputSearchChange(searchData)">搜索</view>
			</view>
		</view>
         <!-- #ifdef MP-WEIXIN -->
		<view class="box" :style='{height: navH+48 + "px"}'></view>
        <!-- #endif -->
        <!-- #ifdef MP-ALIPAY -->
        <view class="box" :style='{height: 48 + "px"}'></view>
        <!-- #endif -->
        <block v-if="!showList">
			<view class="tags" v-if="historyList.length>0">
				<view class="tags-header">
					<text>历史搜索</text>
					<image @click="deleteHistory()" src="http://img1.birdback.org/a/13/c7/13c7ada4ea216d4d4563e9a951fdde3e.png"></image>
				</view>
				<view class="tags-list">
					<block v-for="(item,index) in historyList" :key="index">
						<view :class="searchData == item && isButtonSearch ?'active':''" @click="buttonSearch(item)">{{item}}</view>
					</block>
				</view>
			</view>
			<view class="tags" v-if="hotList.length>0">
				<view class="tags-header">
					<text>热门搜索</text>
					<view></view>
				</view>
				<view class="tags-list">
					<block v-for="(item,index) in hotList" :key="index">
						<view :class="searchData == item && isHotSearch ?'active':''" @click="hotSearch(item.keyword)">{{item.keyword}}</view>
					</block>
				</view>
			</view>
		</block>
		<block v-else>
			<block v-if="!isEmpty">
                <view :style="{height: listHeight + 'px'}" class="list-content">
                    <goods-item 
                        :header          = "header"
                        :goodsList       = "searchGoodsList" 
                        :goodsDetail     = "goodsDetail" 
                        :setting         = "setting" 
                        @addCart         = "addCart()"
                        @decreaseCart    = "decreaseCart()" 
                        @showGoodsDetail = "showGoodsDetail()"
                        @closeGoodsDetail= "closeGoodsDetail()"
                        @selectSetting   = "selectSetting()"
                        @settingInsert   = "settingInsert()"
                        @addDetailCart   = "addDetailCart()"
                        @closeSetting    = "closeSetting()"
                    >
                    </goods-item>
                    <view class="no-more" v-if="noMore">没有更多了哦</view>   
                </view>
			</block>
			<block v-else>
				<view class="empty">
					<image src="http://juhuijia2.birdback.org/mapi/i/home/ku@3x.png"></image>
					<text>抱歉，未能找到您搜索的商家或商品</text>
				</view>
			</block>
		</block> 
        <shop-cart class="shopCart" 
            :storeInfo      = "storeInfo"
            :header         = "header"
            :disable        = "storeInfo.disable" 
            :reserve_start  = "storeInfo.reserve_start" 
            :totalCount     = "totalCount" 
            :totalCount_all = "totalCount_all"
            :totalPrice     = "totalPrice"
            :totalPrice_all = "totalPrice_all"
            :payDesc        = "payDesc"
            :deliveryPrice  = "deliveryPrice"
            :open_oneself   = "storeInfo.open_oneself"
            :cartShow       = "cartShow"
            :carList        = "carList"
            :toView         = "toView"
            :packageFee     = "packageFee"
            :activeList     = "activeList"
            :groupList      = "groupList"
            :self_money     = "self_money"
            :showGetUser_1  = "showGetUser_1"
            :is_master      = "is_master"
            :must           = "must"
            :showGetUserStorage = "showGetUserStorage"
            @toggleList     = "toggleList()" 
            @empty          = "empty()"
            @addCartGoods   = "addCartGoods()"
            @subCartGoods   = "subCartGoods()"
            @pay            = "pay()">
        </shop-cart>
    </view>
</template>

<script>
	import Big       from '../../../common/big.js';
    import uniFly    from 'unifly';
	import request   from '../../../common/request.js';
    import md5       from '../../../common/md5.js';
	import $api_base from '../../../api/api_base.js';
	import topNav    from '@/template/topnav/index.vue';
    import goodsItem from '@/template/goods/index/index.vue';
    import shopCart  from '@/template/shopCart/index/index.vue';
    import event     from '../../../common/event.js';
   
    var carArray1 = [];
    var groupArray= [];
    var carTmp = [];
    var orderNum = 0;
    var discountGoodsNum = 0; 
    var minPrice = 0;//起送價格
	export default {
		components: { topNav, goodsItem, shopCart },
		data() {
			return {
                openId:'',
                sid:'',
                aid: 0,   //相关来源id
				navH:0,
				n:0,
				title: '',
				storeInfo: '',
                deliveryPrice: 0,
                
                carList:[],
                totalCount:0,
                totalPrice:0,
                payDesc:'',
                cartShow:'none',
                packageFee:0,
                fold: true,
                
                group_id: 0,
                groupList: [],
                self_money: 0,
                is_master: false,
                totalPrice_all: 0,
                totalCount_all: 0,
                must: false,
                group_status: 0,
                master_id: '',
                
                toView: 'order0',
                isCheck: false,
                storeId: '',
                group_id: 0,
                header: '',
                showList: false,
                historyList: [],
                hotList: [],
                isEmpty: false,
                focusSearch: true,
                searchData: '',
                isCk: [],
                isButtonSearch: false,
                isHotSearch: false,
                searchGoodsList: [],
                setting: {
                    show: false,
                    item: [],
                    price: 0,
                    showPrice: 0
                },
                goodsDetail: {
                    show: false,
                    index: 0,
                    src: '',
                    title: '',
                    info: '',
                    num: '',
                    price: ''
                },
                listHeight: 0,
                mustCid: 0,
                mustClistKey: 0,
                mustSum: 0,  //必选品总量
                goodsAdd: {},
                goodsKeySub: '',
                goodsKeyAd: '',
                is_super: 0
			}
		},
		onLoad: function(options){
			this.navH = getApp().globalData.navHeight; 
			this.n = getApp().globalData.n;
            this.storeId  = options.storeId || '';
            this.header   = options.header  || '';
            this.title    = options.storeName || '';
            this.group_id = options.group_id || 0;
            this.sid      = options.sid || '';
            let pages     = getCurrentPages();
            let prevPage  = pages[pages.length - 2];
            
            prevPage.$vm.fromPage = 'storeSearch';
            this.is_super        = prevPage.$vm.is_super;
            this.openId          = prevPage.$vm.openId;
            this.aid             = prevPage.$vm.aid;
            this.deliveryPrice   = prevPage.$vm.deliveryPrice;
            this.group_status    = prevPage.$vm.group_status;
            this.master_id       = prevPage.$vm.master_id;
            this.storeInfo       = prevPage.$vm.storeInfo;
            this.payDesc         = prevPage.$vm.payDesc;
            this.carList         = prevPage.$vm.carList;
            this.totalCount      = prevPage.$vm.totalCount;
            this.totalPrice      = prevPage.$vm.totalPrice;
            this.packageFee      = prevPage.$vm.packageFee;
            this.activeList      = prevPage.$vm.activeList;
            minPrice             = prevPage.$vm.minPrice; 
            this.group_id        = prevPage.$vm.group_id;
            this.self_money      = prevPage.$vm.self_money;
            this.groupList       = prevPage.$vm.groupList;
            this.is_master       = prevPage.$vm.is_master;
            groupArray           = prevPage.$vm.groupArray;
            this.totalPrice_all  = prevPage.$vm.totalPrice_all;
            this.totalCount_all  = prevPage.$vm.totalCount_all;
            this.must            = prevPage.$vm.must;
            this.mustSum         = prevPage.$vm.mustSum;
            this.mustCid         = prevPage.$vm.mustCid;
            this.mustClistKey    = prevPage.$vm.mustClistKey;
            let storeData = uni.getStorageSync("STOREDATA"); 
            carArray1     = event.arrToObj(storeData.carArray1);
            this.loadHotList();
            this.loadHistoryList();  
		 },
		 methods:{
            setHeight: function () {
                var self = this;
                uni.getSystemInfo({
                    success(res) {
                        self.listHeight = res.windowHeight - 107 - getApp().globalData.navHeight;
                    }
                });
            },
            loadHotList:function(){
                var self = this;
                var store_id = self.storeId;
                $api_base.post($api_base.getKeywords,{ store_id: store_id },1).then(function(res) {
                    let data = res.data;
                    if (data.ok == 1) {
                      var hotList = data.data || [];
                      self.hotList = hotList;
                    } else {
                      return false;
                    }
                });
            },
            loadHistoryList:function(){
                var self = this;
                var store_id = self.storeId;
                $api_base.post($api_base.getHistoryWords,{ store_id: store_id }).then(function(res) {
                    let data = res.data;
                    if (data.ok == 1) {
                      var historyList  = data.data || [];
                      self.historyList = historyList;
                    } else {
                      return false;
                    }
                });
            },
            deleteHistory: function () {
                var self = this;
                var store_id = self.storeId;
                $api_base.post($api_base.delHistoryWords,{ store_id: store_id },1).then(function(res) {
                    let data = res.data;
                    if (data.ok == 1) {
                      var historyList  = data.data || [];
                      self.historyList = historyList;
                    } else {
                      return false;
                    }
                });
            },
            buttonSearch: function (e) {
                var self = this;
                this.searchData     = e;
                this.isHotSearch    = false;
                this.isButtonSearch = true; 
                this.focusSearch    = false;
                this.showList       = true;
                self.loadSearchList(true);
            },
            hotSearch: function (e) {
                var self = this;
                this.searchData     = e; 
                this.isHotSearch    = true; 
                this.isButtonSearch = false; 
                this.focusSearch    = false;
                self.loadSearchList(true);
            },
            loadSearchList: function(){
                var self = this;
                var store_id = self.storeId;
                var keyword  = self.searchData;
                var carList  = this.carList;
                var list     = [];
                var group_id = self.group_id;
                $api_base.post($api_base.goodsSearch,{ store_id: store_id, keyword: keyword, group_id: group_id }).then(function(res) {
                    let data = res.data;
                    if (data.ok == 1) {
                        var searchGoodsList = data.data || [];
                        var isEmpty = searchGoodsList.length === 0 ? true : false;
                        if (searchGoodsList.length > 0) {
                            searchGoodsList.map(function (i, k) {
                              for (var K in carList) {
                                if (carList[K].id == i.id) {
                                  if (carList[K].stdClass.spec !== undefined) {
                                    i.sel_out = 1;
                                    i.spec.map(function (n, m) {
                                      if (n.id == carList[K].stdClass.spec.id) {
                                        i.Count += carList[K].num;
                                        i.spec[m].num = i.spec[m].num - carList[K].num;
                                      }
                                      if (i.spec[m].num > 0) i.sel_out = 0;
                                    });
                                  }else {
                                    i.sel_out = 1;
                                    i.Count += carList[K].num;
                                    i.num = i.num - carList[K].num;
                                    if (i.num > 0) i.sel_out = 0;
                                  }
                                }
                              }
                              list.push(i);
                            });
                        }
                        self.searchGoodsList = list; 
                        self.showList = true;
                        self.isEmpty  = isEmpty;
                        self.setHeight();
                    } else {
                      return false;
                    }
                });
            },
            inputChange: function(e){
                var self = this;
                if(e.detail.value.length==0){
                    self.searchData = "";
                    self.showList = false;
                    self.isButtonSearch = false;
                    self.isHotSearch = false;
                    self.searchGoodsList = [];
                }
            },
            inputSearchChange: function (e) {
                var value = e;
                var len = e.length;
                var self = this;
                if (value.trim() != "" && len > 0) {
                    self.searchData = value.trim();
                    (function (len) {
                        var value = self.searchData;
                        if (len == value.length && len > 0) {
                          self.searchData = value;
                          self.loadSearchList(true);
                        }
                    }(len));
                } else {
                    self.searchData = ""; 
                    self.showList = false; 
                    self.isButtonSearch = false;
                    self.isHotSearch = false;
                }
            },
            emptyInput: function(){
                this.searchData = ""; 
                this.showList  = false; 
                this.searchGoodsList = []; 
                this.isButtonSearch = false; 
                this.isHotSearch = false; 
                this.focusSearch = true;
            },
            showGoodsDetail: function (e) {
                var index = e.currentTarget.dataset.index;
                var goods = this.searchGoodsList[index];
                this.goodsDetail = {
                        show: true,
                        src: goods.icon,
                        title: goods.allName,
                        info: goods.allDesc,
                        num: goods.buy_num,
                        price: goods.price,
                        index: index,
                        sel_out: goods.sel_out
                    }
            },
            addDetailCart: function(e){
                var index = e.currentTarget.dataset.index;
                this.goodsDetail = {show: false};
                this.addCart({currentTarget: {dataset: {index: index}}});
            },
            closeGoodsDetail: function () {
                this.goodsDetail = {show:false};
            },
            selectSetting:function(e) {
                var idx = e.currentTarget.dataset.idx;
                var index = e.currentTarget.dataset.index;
                var item = this.setting.item[idx];
                var value = item.value[index];
                var price = 0;
                item.value.map(function (i, k) {
                  if (i.id === value.id) {
                      item.value[k].current = 1;
                      price = i.price;
                  } else {
                      item.value[k].current = 0;
                  }
                });
                var setting = this.setting;
                setting.item[idx] = item;
                if (item.type === 'spec') {
                  setting.price = price;
                }         
                this.setting = setting;
            },
            closeSetting: function() {
                this.setting = {show: false};
            },
            toggleList: function () {
                if ((this.header != "buy_together" && !this.totalCount) || (this.header == "buy_together" && this.totalCount_all == 0)) {   
                    return;
                }
                var self = this;
                var minPrice = self.storeInfo.start_send_price;
                var totalCount_all = 0;
                var must = false;
                var mustSum = self.mustSum;
                var mustCid = self.mustCid;
                if ( self.cartShow == 'none' && self.header == "buy_together" ){
                    $api_base.post_new($api_base.groupInfo,{ wxapp_id: self.openId, group_id: self.group_id }).then(function(res) {
                        let data = res.data;
                        if (data.ok == 1) {
                            groupArray = data.data || [];
                            for (let i in groupArray) {
                                for (let j in groupArray[i].goods_list) {
                                    totalCount_all += groupArray[i].goods_list[j].num;
                                }
                            }
                            var total_money = data.total_money || 0;
                            var diff = minPrice - total_money;
                            diff = new Big(diff).round(2).toString();
                            var totalPrice = new Big(total_money).round(2).toString();
                            var orderList = data.order_list || [];
                            if (mustCid != 0) {
                                const index = orderList.findIndex(orderList => orderList.category_id == mustCid);
                                if (index >= 0) {
                                  must = false;
                                } else {
                                  must = true;
                                }
                            }
                            self.group_status   = data.group_status;
                            self.groupList      = data.data || [];
                            self.totalCount_all = totalCount_all;
                            self.totalPrice_all = parseFloat(totalPrice);
                            self.self_money     = data.self_money || 0;
                            self.diffPrice      = diff;
                            self.must           = must;
                          //  self.newGoodsList();
                        }
                    }); 
                }
                this.fold = !this.fold;
                this.cartShowMethod(this.fold)
            },
            cartShowMethod: function (fold) {
                if (fold == false) {
                    this.cartShow = 'block';
                } else {
                    this.cartShow = 'none';
                }
            },
            empty: function(e) {
                var self = this;
                var openId = self.openId;
                var header = self.header;
                var cartShow = '';
                var totalCount_all = 0;
                var isSearch = self.isSearch;
                uni.showModal({
                    content: '确定要清空购物车吗？',
                    success: function (res) {
                        if (res.confirm) {
                            if(header == 'buy_together'){
                                var groupList = self.data.groupList;
                                for( let i in groupList){
                                    if(openId == groupList[i].wxapp_id){
                                        groupList[i].goods_list.splice(0, groupList[i].goods_list.length)
                                    }
                                    totalCount_all += groupList[i].goods_list.length;
                                }
                                if (totalCount_all > 0) {
                                    cartShow = 'block';
                                } else {
                                    cartShow = 'none';
                                }
                                carArray1 = [];
                                self.carList = []; 
                                self.groupList = groupList; 
                                self.cartShow = cartShow;
                                self.confirmGoods();
                            }else{                              
                                var searchGoods = [];
                                searchGoods = self.searchGoodsList;
                                searchGoods.map(function (i, K) {
                                    searchGoods[K].Count = 0;
                                });
                                carArray1 = [];
                                carTmp = [];
                                orderNum = 0;
                                discountGoodsNum = 0;
                                self.carList = []; 
                                self.cartShow = 'none', 
                                self.searchGoodsList = searchGoods;
                                self.calTotalPrice(carArray1);
                                self.totalCount = 0;
                                self.totalPrice = 0;
                                self.payDesc = self.payDesc();
                                self.loadReData()
                            } 
                        }
                    }
                })
            }, 
            loadReData:function(){
                let carList = this.carList;
                let pages = getCurrentPages();
                let prevPage     = pages[pages.length - 2];
                let goodsList    = prevPage.$vm.goodsList;
                let categoryList = prevPage.$vm.categoryList;
                let list = [];
                if (goodsList.length > 0) {
                    if(this.is_super == 1){
                        goodsList.map(function (i, k) {
                            if(carList.length>0){
                                for (var K in carList) {
                                    if (carList[K].id == i.id) {
                                        if (carList[K].stdClass.spec !== undefined) {
                                            i.sel_out = 1;
                                            i.spec.map(function (n, m) {
                                                if (n.id == carList[K].stdClass.spec.id) {
                                                    i.Count += carList[K].num;
                                                    i.spec[m].num = i.spec[m].num - carList[K].num;
                                                }
                                                if (i.spec[m].num > 0) i.sel_out = 0;
                                            });
                                        } else {
                                            i.sel_out = 1;
                                            i.Count += carList[K].num;
                                            i.num = i.num - carList[K].num;
                                            if (i.num > 0) i.sel_out = 0;
                                        }
                                    }
                                }
                            }else{
                                i.Count = 0;
                            }
                          list.push(i);
                        });
                    }else{
                        categoryList.map(function (i, k) {
                            i.count = 0;
                        });
                        for(let i in goodsList){
                            for(let l in goodsList[i]){ 
                                goodsList[i][l].Count = 0;
                                if(carList.length>0){
                                    for(let K in carList){
                                        if(carList[K].id == goodsList[i][l].id){
                                            if (carList[K].stdClass.spec !== undefined) {
                                                goodsList[i][l].sel_out = 1;
                                                goodsList[i][l].spec.map(function (n, m) {
                                                    if (n.id == carList[K].stdClass.spec.id) {
                                                        goodsList[i][l].Count += carList[K].num;
                                                        goodsList[i][l].spec[m].num = goodsList[i][l].spec[m].num - carList[K].num;
                                                        categoryList[i].count = categoryList[i].count + carList[K].num;
                                                    }
                                                    if (goodsList[i][l].spec[m].num > 0) goodsList[i][l].sel_out = 0;
                                                });
                                            } else {
                                                goodsList[i][l].sel_out = 1;
                                                goodsList[i][l].Count += carList[K].num;
                                                categoryList[i].count = categoryList[i].count + carList[K].num;
                                                goodsList[i][l].num = goodsList[i][l].num - carList[K].num;
                                                if (goodsList[i][l].num > 0) goodsList[i][l].sel_out = 0;
                                            }
                                        }
                                    }
                                }else{
                                   // goodsList[i][l].Count = 0;
                                    categoryList[i].count = 0;
                                }
                            }
                        }
                    }  
                }
                if(this.is_super== 1){
                    prevPage.$vm.goodsList = list; 
                }else{
                    prevPage.$vm.goodsList = goodsList; 
                }
                prevPage.$vm.categoryList  = categoryList; 
                prevPage.$vm.carList       = this.carList;
                prevPage.$vm.totalCount    = this.totalCount;
                prevPage.$vm.totalPrice    = this.totalPrice; 
                prevPage.$vm.payDesc       = this.payDesc; 
                prevPage.$vm.packageFee    = this.packageFee; 
                let searchData = {
                    carArray1 : event.objToArr(carArray1)
                }
                uni.setStorageSync("SEARCHDATA", searchData); 
            },    			
            //规格设置
            settingInsert:function() {    //选好了触发
                var setting = this.setting;
                this.searchGoodsList[setting.index].setting = setting.item;
                this.insertCart(this.searchGoodsList[setting.index], setting.index, 1)
                this.closeSetting();   
            },
            addCart: function(e){
                var index = e.currentTarget.dataset.index;   //加号index
                var goods = '';
                goods     = this.searchGoodsList[index];   //当前选中商品
                var spec  = goods.spec || [];
                var attr  = goods.attr || [];        
                var item  = [];
                if (spec.length > 0) {   //规格属性
                    var price = 0;
                    var isFirst = 1;
                    spec.map(function (i, k) {
                        if (i.num > 0 && isFirst) {
                            isFirst = 0;
                            spec[k].current = 1;
                            price = i.price;
                        } else spec[k].current = 0;
                    });
                    item.push({"name": "规格", "value": spec, "type": "spec"});
                }
                if (attr.length > 0) {   //规格属性
                    attr.map(function (i) {
                        var attribute = i.attribute.split('|');
                        var valueObj = [];
                        attribute.map(function (name, id) {
                            valueObj.push({"name": name, "id": id, "price": 0, "current": id === 0 ? 1 : 0});
                        });
                        item.push({"name": i.name, "value": valueObj, "type": "attr"});
                    });
                }
                if (item.length > 0) {
                    this.setting = {show: true, item: item, index: index, name: goods.name, price: price}
                } else {
                    this.insertCart(goods, index)
                }
            },
            addCartGoods: function(e){
                var key   = e.currentTarget.dataset.key;
                var id    = e.currentTarget.dataset.id;
                var goods = [];
                goods     = this.searchGoodsList || [];
                var isSelOut = 0;
                var isFind = false;
                this.goodsKeyAd = key; 
                this.goodsKeySub = '';
                if (this.header != 'buy_together') {
                   if (carArray1[key].stdClass.spec !== undefined) {
                       goods.map(function (i, K) {
                           if (i.id === id) {
                               isFind = true;
                               var selOut = 1;
                               i.spec.map(function (n, m) {
                                   if (carArray1[key].stdClass.spec.id == n.id) {
                                       if (goods[K].spec[m].num <= 0) {
                                           isSelOut = 1;
                                       } else {
                                           goods[K].spec[m].num--;
                                       }
                                   }
                                   var num = goods[K].spec[m].num;
                                   if (num > 0) selOut = 0;
                                   goods[K].sel_out = selOut;
                               });
                           }
                       });
                       if (!isFind) {
                           if (carArray1[key].num - carArray1[key].stdClass.spec.maxNum >= 0) {
                               isSelOut = 1;
                           }
                       }
                   } else {
                       var selOut = 1;
                       goods.map(function (i, K) {
                           if (i.id === id) {
                               isFind = true;
                               if (goods[K].num <= 0) {
                                   isSelOut = 1;
                               } else {
                                   goods[K].num--;
                               }
                               var num = goods[K].num;
                               if (num > 0) selOut = 0;
                               goods[K].sel_out = selOut;
                           }
                       });
                       if (!isFind) {
                           if (carArray1[key].num - carArray1[key].goods.maxNum >= 0) {
                               isSelOut = 1;
                           }
                       }
                   }
                   if (isSelOut > 0) {
                       uni.showToast({title: '已售完', icon: 'none', duration: 2000});
                       return false;
                   }
                   goods.map(function (i, K) {
                       if (i.id === id) goods[K].Count++;
                   });
                   carTmp.unshift({id: id, key: key});
                   carArray1[key].num = carArray1[key].num + 1;
                   this.callCarPrice(key);
                }
                this.callCarList();
                this.searchGoodsList = goods;
                this.cartShow = 'block';
                this.calTotalPrice();
                this.payDesc = this.payDescFunc();
            },
            decreaseCart: function(e){
                var self = this;
                var index = e.currentTarget.dataset.index;
                var id = e.currentTarget.dataset.id;
                var delKey = null;
                var goodsList = [];
                goodsList = this.searchGoodsList || []; 
                if(this.header != 'buy_together'){
                    for (var k in carTmp) {
                        if (carTmp[k].id == id) {
                            delKey = carTmp[k].key;
                            carTmp.splice(k, 1);
                            break;
                        }
                    }
                    if (delKey === null || carArray1[delKey] === undefined) return false;
                    if (carArray1[delKey].stdClass.spec !== undefined) {
                        goodsList[index].Count--;
                        goodsList[index].spec.map(function (n, m) {
                            if (carArray1[delKey].stdClass.spec.id == n.id) {
                                goodsList[index].spec[m].num++;
                            }
                            var num = goodsList[index].spec[m].num;
                            if (num > 0) goodsList[index].sel_out = 0;
                        });
                    } else {
                        goodsList[index].Count--;
                        goodsList[index].num++;
                        var num = goodsList[index].num;
                        if (num > 0) goodsList[index].sel_out = 0;
                    }
                    if (carArray1[delKey].num - 1 === 0) {  //商品清零
                        var numDiscount = carArray1[delKey].goods.discount.num_discount || 0;   //折扣限购份数
                        var openDiscount = carArray1[delKey].goods.open_discount || 0;
                        if (numDiscount > 0 && openDiscount > 0) discountGoodsNum--;  //享受折扣的数
                        delete carArray1[delKey];            
                    } else {
                        carArray1[delKey].num = carArray1[delKey].num - 1;
                        this.callCarSubPrice(delKey);
                    }
                    discountGoodsNum = 0;  //已享受的折扣
                    var goodsDiscount = this.storeInfo.goods_discount || 0;  //总共折扣限购份数
                    for (var k in carArray1) {
                        var num_discount = carArray1[k].goods.discount.num_discount || 0; //该商品折扣限购份数
                        var lastDiscount1 = goodsDiscount - discountGoodsNum;   //总共剩余的折扣份数
                        var showPrice = carArray1[k].showPrice || carArray1[k].price;
                        var openDiscount = carArray1[k].goods.open_discount;
               
                        if (lastDiscount1 > 0) {  //还有可折扣数
                            if (num_discount > 0 && openDiscount > 0) { //该商品有可折扣数
                                if (carArray1[k].num <= num_discount) { // 该商品购买量 小于 该商品折扣份数
                                    carArray1[k].money = carArray1[k].num * carArray1[k].price;
                                    discountGoodsNum += carArray1[k].num;
                                    carArray1[k].discountNum = carArray1[k].num;
                                } else {  //该商品购买量 大于 该商品折扣份数
                                    let t1 = num_discount * carArray1[k].price;
                                    let t2 = carArray1[k].num - num_discount
                                    carArray1[k].money = t1 + t2 * showPrice;
                                    discountGoodsNum += num_discount;
                                    carArray1[k].discountNum = num_discount;
                                }
                            } else {
                                num_discount = 0;
                                carArray1[k].money = carArray1[k].num * showPrice;
                            }
                        } else {  //没有折扣了 
                            lastDiscount1 = 0;
                            carArray1[k].money = carArray1[k].num * showPrice;
                            discountGoodsNum += 0;
                            carArray1[k].discountNum = 0;
                        }
                    } 
                    this.searchGoodsList = goodsList;
                }
                this.goodsKeySub = id;
                this.goodsKeyAd  = '';
                this.callCarList();
                this.calTotalPrice();
                this.payDesc = this.payDescFunc();
                //关闭弹起
                if (carTmp.length === 0 && this.header != 'buy_together') {
                    this.cartShow = 'none';
                }
            },
            subCartGoods: function(e){
                var key = e.currentTarget.dataset.key;
                var id = e.currentTarget.dataset.id;
                var goods = [];
                goods = this.searchGoodsList || [];
                this.goodsKeySub = key;
                this.goodsKeyAd = '';
                for (var k in carTmp) {
                    if (carTmp[k].key === key) {
                        carTmp.splice(k, 1);
                        break;
                    }
                }
                if (this.header != "buy_together"){
                    if (key === '' || carArray1[key] === undefined) return false;
                    if (carArray1[key].stdClass.spec !== undefined) {
                        goods.map(function (i, K) {
                            if (i.id === id) {
                                goods[K].Count--;
                                i.spec.map(function (n, m) {
                                    if (carArray1[key].stdClass.spec.id == n.id) {
                                        goods[K].spec[m].num++;
                                    }
                                    var num = goods[K].spec[m].num;
                                    if (num > 0) goods[K].sel_out = 0;
                                });
                            }
                        });
                    } else {
                        goods.map(function (i, K) {
                            if (i.id === id) {
                                goods[K].Count--;
                                goods[K].num++;
                            }
                            var num = goods[K].num;
                            if (num > 0) goods[K].sel_out = 0;
                        });
                    }
                    if (carArray1[key].num - 1 === 0) {
                        var numDiscount = carArray1[key].goods.discount.num_discount || 0;
                        var openDiscount = carArray1[key].goods.open_discount || 0;
                        if (numDiscount > 0 && openDiscount > 0) discountGoodsNum--;
                        delete carArray1[key];
                    } else {
                        carArray1[key].num = carArray1[key].num - 1;
                        this.callCarSubPrice(key);
                    }
                    discountGoodsNum = 0;  //已享受的折扣
                    var goodsDiscount = this.storeInfo.goods_discount || 0;  //总共折扣限购份数
                    for (var k in carArray1) {
                        var num_discount = carArray1[k].goods.discount.num_discount || 0; //该商品折扣限购份数
                        var lastDiscount1 = goodsDiscount - discountGoodsNum;   //总共剩余的折扣份数
                        var showPrice = carArray1[k].showPrice || carArray1[k].price;
                        var open_discount = carArray1[k].goods.open_discount;
                
                        if (lastDiscount1 > 0) {  //还有可折扣数
                            if (num_discount > 0 && open_discount > 0) { //该商品有可折扣数
                                if (carArray1[k].num <= num_discount) { // 该商品购买量 小于 该商品折扣份数
                                    carArray1[k].money = carArray1[k].num * carArray1[k].price;
                                    discountGoodsNum += carArray1[k].num;
                                    carArray1[k].discountNum = carArray1[k].num;
                                } else {  //该商品购买量 大于 该商品折扣份数
                                    let t1 = num_discount * carArray1[k].price;
                                    let t2 = carArray1[k].num - num_discount
                                    carArray1[k].money = t1 + t2 * showPrice;
                                    discountGoodsNum += num_discount;
                                    carArray1[k].discountNum = num_discount;
                                }
                            } else {
                                num_discount = 0;
                                carArray1[k].money = carArray1[k].num * showPrice;
                            }
                        } else {  //没有折扣了 
                            lastDiscount1 = 0;
                            carArray1[k].money = carArray1[k].num * showPrice;
                            discountGoodsNum += 0;
                            carArray1[k].discountNum = 0;
                        }
                    } 
                }
                this.goodsList = goods;
                this.callCarList();
                this.calTotalPrice();
                this.payDesc = this.payDescFunc();
                //关闭弹起
                if ( this.header != "buy_together" && carTmp.length === 0 ){
                    this.cartShow = 'none';
                }else{
                    this.cartShow = 'block';
                }   
            },
            //添加到购物车
            insertCart: function(goods, index) {
                var stdClass = new Object();
                var hashStr = '';
                var goodsList = [];
                goodsList = this.searchGoodsList || [];   // 搜索菜单列表  
                var self = this;
                var header = self.header;
                //列表数量+1
                goodsList[index].Count++;   //当前菜品选中的个数
                hashStr += goods.id + '-';
                //总金额
                var priceIncr = goods.price;  //价格
                var showPriceIncr = goods.show_price || 0;   //原价
                var settingArr = [];  // 后端验证的描述信息集合
                var showDesc = [];   //显示的 描述信息集合
                var isSpec = 0;
                //价格计算
                if (goods.setting !== undefined && goods.setting.length > 0) {
                    goods.setting.map(function (e) {
                        if (e.type === 'spec' && e.value.length > 0) {
                            isSpec = 1;
                            e.value.map(function (i) {
                                if (i.current === 1) {
                                    priceIncr = i.price;
                                    showPriceIncr = i.show_price;
            
                                    stdClass.spec = i;
                                    hashStr += i.id + '-';
                                    if (i.name !== 'x') showDesc.push(i.name);
                                    settingArr.push(i.name);
                                    goodsList[index].spec.map(function (m, M) {
                                        if (m.id == i.id) {
                                            goodsList[index].spec[M].num--;
                                        }
                                    });
                                }
                                var selOut = 1;
                                goodsList[index].spec.map(function (m, M) {
                                    var num = goodsList[index].spec[M].num;
                                    if (num > 0) selOut = 0;
                                    goodsList[index].sel_out = selOut;
                                });
                            });
                        }
                        if (e.type === 'attr' && e.value.length > 0) {
                            e.value.map(function (i, k) {
                                if (i.current === 1) {
                                    if (stdClass.attr === undefined) {
                                        stdClass.attr = [];
                                    }
                                    stdClass.attr.push(i);
                                    hashStr += i.name + '-';
                                    if (i.name !== 'x') {
                                        showDesc.push(i.name);
                                    }
                                    settingArr.push(i.name);
                                }
                            });
                        }
                    });
                }
                if (isSpec === 0) {
                    goodsList[index].num--;
                    if (goodsList[index].num <= 0) {
                        goodsList[index].sel_out = 1;
                    }
                }
                hashStr = md5.hex_md5(hashStr);
                if (carArray1[hashStr] === undefined) {
                    orderNum++;
                    carArray1[hashStr] = {
                        id             : goods.id, 
                        orderNum       : orderNum, 
                        discountNum     : 0,            
                        goods          : goods, 
                        stdClass        : stdClass,
                        key            : hashStr, 
                        price           : priceIncr,      //折后价格
                        showPrice       : showPriceIncr,   //原价
                        num           : 1,            //购买数量
                        money          : 0,            //应付价格
                        index           : index,
                        desc            : settingArr.join('，'), 
                        showDesc        : showDesc.join('，'),
                        box_id          : goods.box_id,
                        food_box_money  : goods.food_box_money,
                        category_id     : goods.category_id
                    };
                    self.callCarPrice(hashStr);
                } else {
                    carArray1[hashStr].num = carArray1[hashStr].num + 1;
                    self.callCarPrice(hashStr);
                }
                if(self.header == "buy_together"){
                    carArray1[hashStr].num = 1;
                }
                let tmpcar={
                    id            : carArray1[hashStr].id,
                    orderNum      : carArray1[hashStr].orderNum,
                    discountNum   : carArray1[hashStr].discountNum,
                    name          : carArray1[hashStr].goods.name,
                    stdClass      : carArray1[hashStr].stdClass,
                    key           : carArray1[hashStr].key,
                    num           : carArray1[hashStr].num,
                    desc          : carArray1[hashStr].desc,
                    showDesc      : carArray1[hashStr].showDesc,
                    price         : carArray1[hashStr].price,
                    box_id        : carArray1[hashStr].box_id,
                    food_box_money: carArray1[hashStr].food_box_money,
                    category_id   : carArray1[hashStr].category_id
                };
                carTmp.unshift({id: goods.id, key: hashStr});
                this.searchGoodsList = goodsList;
                this.goodsAdd = tmpcar;
                this.goodsKeySub = '';
                this.goodsKeyAd = '';
                this.callCarList();
                this.calTotalPrice();
                this.payDesc = this.payDescFunc();
            },
            callCarSubPrice: function (hashStr) {   //减号商品不清零价格计算
                var price = carArray1[hashStr].price;
                var showPrice = carArray1[hashStr].showPrice || 0;
                var buyNum = carArray1[hashStr].num;   //该商品购买量
                let goodsDiscount = this.storeInfo.goods_discount || 0;  //总共折扣限购份数
            },
            decreaseShopCart: function (e) {
                this.decreaseCart(e);
            },
            callCarPrice: function (hashStr) {   //添两个➕ 时触发的价格计算
                var price =  Number(carArray1[hashStr].price);   //折扣价
                var showPrice = Number(carArray1[hashStr].showPrice) || 0;  //原价
                var buyNum = carArray1[hashStr].num;   // 购买数量
                if (carArray1[hashStr].goods.open_discount > 0) {
                    var numDiscount = carArray1[hashStr].goods.discount.num_discount || 0;
                    var share_discount = carArray1[hashStr].goods.discount.share_discount || 0;
                    var goodsDiscount = this.storeInfo.goods_discount || 0;
                    if (numDiscount > 0 && buyNum === (numDiscount + 1) && showPrice > 0 && (goodsDiscount <= 0 || (goodsDiscount - discountGoodsNum) > 0)) {
                        wx.showToast({title: '折扣菜品限购' + numDiscount + '份，超出' + numDiscount + '份恢复原价', icon: "none"});
                    } else if (goodsDiscount > 0 && (goodsDiscount - discountGoodsNum) === 0) {
                        wx.showToast({title: '每单折扣商品限购' + goodsDiscount + '份，超出' + goodsDiscount + '份恢复原价', icon: "none"});
                    } else if (buyNum === 1 && share_discount == 0) {
                        wx.showToast({title: '满减与折扣商品不同享', icon: "none"});
                    }
                    if (numDiscount > 0 && (buyNum > numDiscount || (goodsDiscount > 0 && (goodsDiscount - discountGoodsNum) == 0)) && showPrice > 0) {
                        carArray1[hashStr].money += showPrice;
                    } else {
                        carArray1[hashStr].money += price; //折扣方式计算 购买数量不大于限制
                        carArray1[hashStr].discountNum++;
                        discountGoodsNum++;
                    }
                } else {
                    carArray1[hashStr].money += price; //不带折扣方式计算
                }
            },
            callCarList: function () {  //购物车列表
                var self = this;
                var carList = [];
                var cartShow = self.cartShow;
                var packageFee = self.storeInfo.package_bag_money;
                for (var k in carArray1) {
                    carArray1[k].money = parseFloat(new Big(carArray1[k].money).round(2).toString());
                    if (self.header != "buy_together") {
                        carList.push(carArray1[k]);
                    }
                }
                if (self.header == "buy_together") {
                    self.changeGroupList();
                }
                for(let i in carList){
                    let fee = carList[i].food_box_money * carList[i].num
                    packageFee += fee;
                }
                packageFee = parseFloat(new Big(packageFee).round(2).toString());
                this.carList = carList;
                this.packageFee = packageFee;
            },
            //计算总价
            calTotalPrice: function () {
                var totalPrice = 0;
                var totalCount = 0;
                var packageFee = this.packageFee;
                var must = false;
                for (var k in carArray1) {
                    totalPrice += carArray1[k].money;
                    totalCount += carArray1[k].num;
                }
                if (totalCount == 0 ){
                    packageFee = 0;
                }
                totalPrice = new Big(totalPrice + packageFee).round(2).toString();
                let l = carArray1.length;
                if (l > 0) {
                  if (data.must_cid != 0) {
                    const index = carArray1.findIndex(carArray1 => carArray1.category_id == mustCid);
                    if (index > 0) {
                      must = false;
                    } else {
                      must = true;
                    }
                  }
                }
                this.totalPrice = parseFloat(totalPrice); 
                this.totalCount = totalCount;
                this.must = must;
                this.loadReData()
            },
            payDescFunc: function() {
                var self = this;
                var storeInfo = self.storeInfo;
                var carList = self.carList;
                var sid = self.sid;
                var listServiceType = getApp().globalData.listServiceType;
                var mustSum = self.mustSum;
                var mustCid = self.mustCid;
                if (self.sid === 'group' || self.sid === 'share_group') {
                    if (self.openGroupActive === false) {
                        return '暂无班次';
                    }
                }
                let l = carList.length;
                if(mustSum > 0){
                    if (l > 0) {
                      const index = carList.findIndex(carList => carList.category_id == mustCid);  
                      if (index < 0){
                          self.must = true;
                         // return '下单前请选必选品';
                        }else{
                          if (self.totalPrice < minPrice){
                            var diff = minPrice - self.totalPrice;
                            diff = new Big(diff).round(2).toString();
                            self.must = false;
                            return '还差' + diff + '元起送';
                          }else{
                            self.must = false;
                            return '去结算';
                          }
                        }
                    }else{
                      self.must = true;
                    //  return '下单前请选必选品';
                    }
                }
                if (sid == "oneself" || listServiceType != 0 || self.storeInfo.open_oneself == 2) {  //自取
                    minPrice = self.storeInfo.invite_start_send_price || 0;
                } else {
                    minPrice = self.storeInfo.start_send_price || 0;
                }  
                if (self.totalPrice === 0) {
                    if ( sid == "oneself" || listServiceType != 0 ) {  //自取     
                        return `￥${minPrice}元起自取`;
                    }else{
                        if ( self.storeInfo.open_oneself == 2 ){
                            return `￥${minPrice}元起自取`;
                        }else{
                            return `￥${minPrice}元起送`; 
                        }
                    }  
                } else if (self.totalPrice < minPrice) {
                    var diff = minPrice - self.totalPrice;
                    diff = new Big(diff).round(2).toString();
                    if (sid == "oneself" || listServiceType != 0) {  //自取     
                        return '还差' + diff + '元自取';
                    } else {
                        if (self.storeInfo.open_oneself == 2){
                            return '还差' + diff + '元自取';
                        }else{
                            return '还差' + diff + '元起送';
                        }
                    }  
                } else {
                    return '去结算';
                }   
            },
            changeGroupList: function(){
                var self = this;
                var carList = [];
                var groupList = self.groupList;
                var goodsAdd = self.goodsAdd;
                var goodsKeySub = self.goodsKeySub;
                var goodsKeyAd = self.goodsKeyAd;  //购物车添加商品的id
                var group_status = self.group_status;
                if(groupList.length==0){
                    carList.push(goodsAdd);
                }else{
                    for (let m in groupList) {   //添加新增的菜单
                        if (groupList[m].wxapp_id == self.openId) { //当前用户
                            if (groupList[m].goods_list.length > 0) {
                                let ex = false;
                                let index = 0;
                                let subIndex = 0;
                                for (let a in groupList[m].goods_list) {
                                    if (goodsKeySub == '' && goodsKeyAd == '') {
                                        if (goodsAdd.id == groupList[m].goods_list[a].id && goodsAdd.showDesc == groupList[m].goods_list[a].showDesc) {
                                            index = a;
                                            ex = true;
                                        }
                                    } else if (goodsKeyAd == '') {
                                        if (goodsKeySub == groupList[m].goods_list[a].key) { //购物车减
                                            if (group_status == 1){
                                                groupList[m].goods_list[a].num--;
                                                if (groupList[m].goods_list[a].num < 1) {
                                                    groupList[m].goods_list.splice(a, 1);
                                                }
                                            }   
                                        } else if (goodsKeySub == groupList[m].goods_list[a].id) {  //商品减
                                            if (group_status == 1){
                                                groupList[m].goods_list[a].num--;
                                                if (groupList[m].goods_list[a].num < 1) {
                                                    groupList[m].goods_list.splice(a, 1);
                                                }
                                            }   
                                            break;
                                        }
                                    } else if (goodsKeySub == '') {     //购物车加
                                        if (goodsKeyAd == groupList[m].goods_list[a].key) {
                                            if (group_status == 1)
                                                groupList[m].goods_list[a].num++;
                                        }
                                    }
                                }
                                if (goodsKeySub == '' && goodsKeyAd == '') {
                                    if (ex) {
                                        if (group_status == 1)
                                            groupList[m].goods_list[index].num++;
            
                                    } else {
                                        groupList[m].goods_list.push(goodsAdd);
                                    }
                                }
                            } else {
                                groupList[m].goods_list.push(goodsAdd);
                            }
                            carList = groupList[m].goods_list;
                        }
                    }
                }
                this.carList = carList;
                this.groupList = groupList;
                this.confirmGoods();
            },    
            confirmGoods: function(){
                var self = this;
                var carList = self.carList;
                var car_list = JSON.stringify(carList);
                $api_base.post_new($api_base.confirmGoods,{ wxapp_id: self.openId, group_id: self.group_id, car_list: car_list, money: self.totalPrice },1).then(function(res) {
                    let data = res.data;
                    if (data.ok == 1) {
                        self.getGroupInfo();
                    } else {
                        self.group_status = data.data.group_status;
                        self.showDisable  = false;
                        self.showDisableModal();
                        self.carList = [];
                        return false
                    }
                });
            },
            getGroupInfo: function () {
                let self = this;
                let list = [];
                let totalCount_all = 0;
                let cartShow    = self.cartShow;
                let minPrice    = self.storeInfo.start_send_price;
                let is_master   = self.is_master;
                let sid         = self.sid;
                let packageFee  = 0;
                let must        = false;
                let mustSum     = self.mustSum;
                let mustCid     = self.mustCid;
                $api_base.post_new($api_base.groupInfo,{ wxapp_id: self.openId, group_id: self.group_id },1).then(function(res) {
                    let data = res.data;
                    if (data.ok == 1) {               
                        groupArray = data.data || [];
                        for(let i in groupArray){
                            for (let j in groupArray[i].goods_list){
                                totalCount_all += groupArray[i].goods_list[j].num;
                            }
                        }
                        var orderList = data.order_list || [];
                        let l = orderList.length;
                        if (mustCid != 0) {
                          if (l > 0) {
                            const index = orderList.findIndex(orderList => orderList.category_id == mustCid);
                            if (index>=0) {
                              must = false;
                            } else {
                              must = true;
                            }
                          } else {
                            must = true;
                          }
                        }
                        if (totalCount_all == 0){
                            cartShow = 'none';
                        }else{
                            packageFee = data.food_box_money + data.package_bag_money;
                            packageFee = new Big(packageFee).round(2).toString();
                        }
                        var total_money = data.total_money || 0;
                        var diff = minPrice - total_money;
                        diff = new Big(diff).round(2).toString();
                        var totalPrice = new Big(total_money).round(2).toString();
                        self.must = must;
                        self.cartShow = cartShow;
                        self.group_status = data.group_status;
                        if (data.master_id == self.openId) {
                            is_master = true;
                        } else {
                            is_master = false;
                        }
                        if ((!is_master) && data.group_status == 2) {
                             if (sid === 'buy_together') {
                                var header = 'buy_together';
                                var sid = "buy_together";
                                getApp().carData = {
                                     storeId: self.storeId,
                                     storeInfo: self.storeInfo,
                                     carList: [],
                                     groupList: []
                                };
                                uni.navigateTo({ url: '/pagesBuy/buy/buy/index?sid=' + sid + '&aid=' + self.aid + '&header=' + header + '&groupId=' + self.group_id + '&is_master=' + is_master + '&listServiceType=' + getApp().globalData.listServiceType });
                            } else {
                                self.showDisableModal();
                                return false
                            }
                        }
                        self.groupList = data.data || [];
                        self.totalCount_all = totalCount_all;
                        self.totalPrice_all = parseFloat(totalPrice);
                        self.self_money = data.self_money || 0;
                        self.diffPrice = diff;
                        self.packageFee = packageFee;
                        self.loadSearchList();  
                    } 
                }); 
            },
            showDisableModal: function(){
                var self = this;
                var text = '';
                var sid = self.sid;
                var aid = self.aid;
                var header = self.header;
                var group_id = self.group_id;
                var is_master = self.is_master;
                if(self.group_status == 2){
                    text = '好友已经提交了订单，您已经无法继续选购商品';
                }else if (self.group_status == 3) {
                    text = '拼单已取消，前往自行下单';
                }else if (self.group_status == 4 || self.group_id == 0) {
                    text = '拼单已完成，前往自行下单';
                } else if (self.group_status == 5) {
                    text = '拼单失败，前往自行下单';
                }
                uni.showModal({
                    title: '',
                    content: text + '',
                    showCancel: false,
                    confirmText: '知道了',
                    confirmColor: '#00B89D',
                    success(res) {
                        if (res.confirm) {
                            let tmpCar = [];
                            if (self.group_status == 2 && !is_master){
                                uni.navigateTo({ url: '/pagesBuy/buy/buy/index?sid=' + sid + '&aid=' + aid + '&header=buy_together&groupId=' + group_id + '&is_master=false' + '&listServiceType=' + getApp().globalData.listServiceType });
                                return false
                            }else if (self.group_status == 3 || self.group_status == 4 || self.group_status == 5){
                                carArray1 = [];
                                self.header = ' '; 
                                self.sid = 'buy_together'; 
                                self.firstIn = false; 
                                self.group_id = 0; 
                                self.groupList= []; 
                                self.totalCount= 0; 
                                self.totalPrice=0;
                                self.setHeight();
                                self.loadSearchList();
                            }
                            self.carList = tmpCar;
                                return false
                        } 
                    }
                })
                return false
            },
            pay:function() {                            
                if (this.header != "buy_together"){
                    if (this.totalPrice < minPrice || this.totalPrice === 0 || this.payDesc == '下单前请选必选品') {
                        return;
                    }
                    if (this.sid === 'group' || this.sid === 'share_group') {
                        if (this.openGroupActive === false) {
                            return;
                        }
                    }
                }
                getApp().carData = {
                    storeId: this.storeId,
                    storeInfo: this.storeInfo,
                    carList: this.carList,
                    groupList: this.groupList
                };
                this.toPay = false;
                var self = this;
                var sid = self.sid;
                var listServiceType = getApp().globalData.listServiceType;
                if (this.header == "buy_together") {
                    if (self.is_master){ 
                      var serviceType = listServiceType ? listServiceType : 0;
                      if(listServiceType == '' ){
                        if (sid == "oneself" && self.storeInfo.open_oneself > 0) {
                          serviceType = self.storeInfo.open_oneself;
                        }
                      } 
                       $api_base.post($api_base.submitGroup,{ wxapp_id: self.openId, group_id: self.group_id, service_type: serviceType, item: 1}).then(function(res) { //发起人比较实付价格和起送价
                            let e = res.data;
                            if (e.ok == 1) {
                                $api_base.post($api_base.checkGroup,{ wxapp_id: self.openId, group_id: self.group_id}).then(function(re) {
                                    let data =re.data;
                                    if (data.ok == 2) {
                                        var stillCheckList = [];
                                        stillCheckList = data.data;
                                        self.showCheckGroup = true; 
                                        self.stillCheckList = stillCheckList
                                        self.toPay = false;
                                    } else {
                                        uni.showModal({
                                            title: '确定去结算吗？',
                                            content: '去结算后，其他人将不可加入或修改商品',
                                            cancelText: '取消',
                                            confirmText: '确认',
                                            confirmColor: '#00B89D',
                                            success(res) {
                                                if (res.confirm) {
                                                    self.toPay = true;
                                                    self.realPay();
                                                } else if (res.cancel) {
                                                    return false
                                                }
                                            }
                                        })
                                    }
                                });   
                            }else if (e.ok == 3){
                                uni.showToast({ title: '当前应付价为'+e.current_price+'元，低于店铺起送价', icon: "none", duration: 2000 })
                                return false;
                            }else{
                                uni.showToast({ title: e.msg, icon: "none", duration: 2000 })
                                return false;
                            }
                        })           
                    }else{
                        $api_base.post_new($api_base.groupInfo,{ wxapp_id: self.openId, group_id: self.group_id}).then(function(res) {
                            let data = res.data;
                            if (data.ok == 1) {
                                self.group_status = data.group_status;
                                if (data.group_status >2 ) {
                                    self.showDisableModal();
                                    return false;
                                } else {
                                    self.toPay = true;
                                    self.realPay();
                                }
                            }
                        })
                    }
                }else{
                    uni.navigateTo({ url: '/pagesBuy/buy/buy/index?sid=' + this.sid + '&aid=' + this.aid + '&listServiceType=' + getApp().globalData.listServiceType });
                }
            },
            realPay:function(){
                var self = this;
                var is_master = self.is_master;
                if(!is_master && self.group_status == 2){
                    uni.navigateTo({ url: '/pagesBuy/buy/buy/index?sid=' + self.sid + '&aid=' + self.aid + '&header=' + self.header + '&groupId=' + self.group_id + '&is_master=' + self.is_master + '&listServiceType=' + getApp().globalData.listServiceType });
                }else{
                    $api_base.post_new($api_base.changeStatus,{ wxapp_id: self.openId, group_id: self.group_id, status: 2 }).then(function(res) {
                        let data = res.data;
                        if (data.ok == 1) {
                            if (is_master) {
                                self.showCheckGroup = false;
                            }
                            uni.navigateTo({ url: '/pagesBuy/buy/buy/index?sid=' + self.sid + '&aid=' + self.aid + '&header=' + self.header + '&groupId=' + self.group_id + '&is_master=' + self.is_master + '&listServiceType=' + getApp().globalData.listServiceType });
                        } else {
                            if(!is_master){
                                uni.navigateTo({ url: '/pagesBuy/buy/buy/index?sid=' + self.sid + '&aid=' + self.aid + '&header=' + self.header + '&groupId=' + self.group_id + '&is_master=' + self.is_master + '&listServiceType=' + getApp().globalData.listServiceType });
                            }else{
                                uni.showToast({ title: '跳转失败，请重新点击去结算', icon: 'none', duration: 2000 });
                                return false;
                            }
                        }
                    });
                } 
            },
		 },
        onPullDownRefresh: function () {
			uni.stopPullDownRefresh();
		},
			/**
			 * 页面上拉触底事件的处理函数
			 */
		onReachBottom: function () {
			this.noMore = true;
		},
		
	}
</script>
<style>
    page{
        background-color: #fff;
    }
</style>
<style lang="scss" scoped>
	@import '../../../pages/goods/index.scss';
    @import '../../../pagesOther/search/index.scss';
    @import 'index.scss';
</style>
